// Copyright 2010 Google Inc. All Rights Reserved.

/**
 * @fileoverview Server-side code for making an API request across domains.
 *
 * @author monsur@google.com (Monsur Hossain)
 */

goog.provide('googleapis.ApiServer');


/**
 * @constructor
 */
googleapis.ApiServer = function() {
};


/**
 * @param {string} headerName The name of the header.
 * @return {boolean} Whether the client is allowed to set this header.
 * @private
 */
googleapis.ApiServer.isValidHeader_ = function(headerName) {
  return (
      headerName === 'Authorization' ||
      headerName === 'Content-Type' ||
      headerName === 'OriginToken' ||
      headerName === 'X-ClientDetails' ||
      headerName === 'X-JavaScript-User-Agent');
};


/**
 * @return {Object} A new XmlHttpRequest object.
 * @private
 */
googleapis.ApiServer.createXhr_ = function() {
  // TODO(monsur): This function is also in gadgets.io.makeXhr(), but its not
  // exposed publicly.  Switch over to that once we can.
  try {
    return new XMLHttpRequest();
  } catch (e) {
  }
  try {
    return new ActiveXObject('Msxml2.XMLHTTP');
  } catch (e) {
  }
  return null;
};


/**
 * @return {string|undefined} Returns the SID value from the cookie, or null if
 *     the SID cookie doesn't exist.
 */
googleapis.ApiServer.getSidValue = function() {
  return goog.net.cookies.get('SID');
};


/**
 * @param {Object} requestObj The RPC requests.
 * @param {Function} callback The function to call with the response.
 */
googleapis.ApiServer.makeRequest = function(requestObj, callback) {
  requestObj = requestObj || {};
  var headers = requestObj['headers'] || {};
  var requests = requestObj['requests'] || [];
  var urlParams = gadgets.util.getUrlParameters();

  headers['Content-Type'] = 'application/json';
  headers['X-JavaScript-User-Agent'] = 'google-api-javascript-client/0.1';

  var xhr = googleapis.ApiServer.createXhr_();
  if (!xhr) {
    throw new Error('XHR not supported');
  }

  var callbackWrapper = function() {
    if (xhr.readyState != 4) {
      return;
    }
    var responseStr = xhr.responseText;
    // TODO(monsur): Can the callback accept an object rather than a string?
    callback(responseStr);
  };

  // TODO(monsur): If the batch request contains only one request, and that
  // request is readonly, turn the request into an RPC GET request and use
  // HTTP GET.
  // ../rpc because the rpc endpoint is one level above static/proxy.html.
  // TODO(uidude) Determine if pretty printing is the right default when
  // we launch.
  xhr.open('POST', '../rpc?pp=1');
  xhr.onreadystatechange = callbackWrapper;

  for (var headerName in headers) {
    // Whitelist headers that can be set.
    if (googleapis.ApiServer.isValidHeader_(headerName)) {
      xhr.setRequestHeader(headerName, headers[headerName]);
    }
  }

  xhr.send(gadgets.json.stringify(requests));
};
